﻿
Sail.widget.ext.grid3 = function(config){
    this.colCheckbox  = false;  
    this.colNumber    = true;
    
    this.singleSelect = false;  
    this.collapsible  = true;
    
    Sail.apply(this, config);
    Sail.widget.ext.superclass.constructor.call(this);
    
    this.btIDPrefix     = "grid_tbar_bt_";
    this.tbarButtons    = [];
    
    this.store = null;
    this.createdGrid = false;
    this.selectIndex = -1;
    this.pageSize = 6;
    
    //-----------------------------------------------------------
    //-----------------------------------------------------------
    this.items = [];
    this.itemsIndex = 0;
    this.delIndex = [];

    this.recordDefine = null;
    
    this.tmpFlag4Act = false; 
    this.bc = 2;

    //-----------------------------------------------------------
    //-----------------------------------------------------------
    this.eventManager = [];

}

Sail.extend(Sail.widget.ext.grid3,Sail.widget.ext,{

    //=============================================================================================
    //=============================================================================================
    bindData : function(){
        var a = arguments,r=null,d=null;
        if(a.length==1){
            r = this.bindRelation;
            d = a[0];
        }else{
            r = a[0];
            d = a[1];
        }
        this.bindDataByArray(r,d);
    },
    bindDataByArray : function(_bindRelation,_dataArray){
        var r = _bindRelation;
        var d = _dataArray;
        
        var _sysflag = (r.sysflag==undefined)?"sysFlag":r.sysflag;
        
        if(r.col){  
            var fieldSource  = r.field;
            var resultSrouce = d[r.result];
            //-----------------------------------------------------------------------------------------
            var newData = [];
            if(resultSrouce.length){
                for(var i=0;i<resultSrouce.length;i++){
                    if(resultSrouce[i][_sysflag]==='0')
                        continue;
                    
                    newData[i]={};
                    Ext.apply(newData[i],resultSrouce[i]);
                }
            }else{
                if(sc.isUpdate()||sc.isView()){
                    if(!(resultSrouce instanceof Array)){
                        if(resultSrouce[_sysflag]!=='0'){
                            newData[0]={};
                            Ext.apply(newData[0],resultSrouce);
                        }
                    }
                }
            }
            this.dataArray = newData;

            //-----------------------------------------------------------------
            //-----------------------------------------------------------------
            for(var i=0;i<newData.length;i++){
              var dsDefine= this.recordDefine;
              var colInfo = Ext.data.Record.create(dsDefine);
              var p = new colInfo(newData[i]);

              this.addnewRecord2Grid(p,false);
            }
            
            //-----------------------------------------------------------------
            //构造store的reader时，如果name包含分级(.)，则替换为*
            //-----------------------------------------------------------------
            /*
            var newDSDefine = [];
            for(var i=0,len=fieldSource.length;i<len;i++){ 
                newDSDefine[i] = fieldSource[i]; 
            }
            //debugger;
            var newStore = new Ext.data.Store({     
		        proxy: new Ext.data.PagingMemoryProxy(this.dataArray),  //数据
		        reader: new Ext.data.ArrayReader({}, newDSDefine)       //行对象定义
            });
            */
            //-----------------------------------------------------------------
            //-----------------------------------------------------------------
            //var theGrid = this.el;
            //theGrid.reconfigure(newStore,theGrid.getColumnModel());
            //theGrid.getStore().load();
            //debugger;
        }
    },

    //=============================================================================================
    //=============================================================================================
    getButtonIndexByText : function(text){
        for(var i=0,len=this.tbarButtons.length;i<len;i++){
            if(this.tbarButtons[i]["text"]==text) return i;
        }
        return -1;
    },
    getButton:function(key){
        var type =  typeof key;
        if(type=="string"){
            var index = this.getButtonIndexByText(key);
            if(index==-1) {
                //alert("没有找到符合条件的按钮！");
                return null;
            }
            var id = this.btIDPrefix+index;
            return this.el.getTopToolbar().items.get(id);
        }else if(type=="number"){
            key = (key==0)?0:key+1;
            return this.el.getTopToolbar().items.get(key);
        }else{
            alert("传递的参数错误！");
        }
        return null;
    },

    getCount : function(){
        return this.el.store.getCount();
    },
    setTitle : function(title){
        this.el.setTitle(title);
    },
    
    //=============================================================================================
    //=============================================================================================
    getFieldsFromCol : function(c){
        var fs = [];
        for(var i=0;i<c.length;i++){
            var haveFlag = this.checkHave(c[i]["dataIndex"],fs);
            if(!haveFlag) fs.push(c[i]["dataIndex"]);
            
            if(c[i]["nameIndex"]){
                var haveFlag = this.checkHave(c[i]["nameIndex"],fs);
                if(!haveFlag) fs.push(c[i]["nameIndex"]);
            }
        }
        return fs;
    },
    checkHave : function(f,a){
        var sa = ","+a.join(",")+",";
        return (sa.indexOf(","+f+",")==-1)?false:true;
    },
    isAddField : function(f,a){
        for(var i=0;i<a.length;i++){
            if((typeof a[i]) =="object"){
                if(a[i].name==f) return true;
            }else{
                if(a[i]==f) return true;
            }
        }
        return false;
    },

    //=============================================================================================
    //处理表头缩放的方法
    //=============================================================================================
    createHeaderByPlugins : function(col){
        var newHeader = col.header;
    
        if(col.plugins.act=='retract'){
            var middleWidth = col.width-10-30;

            var headhtml = "";
            headhtml+="<div id='act-div-left' class='act-retract-left'    style='width:15'></div>";
            headhtml+="<div id='act-div-center' class='act-retract-middle'  style='width:"+middleWidth+";'>"+col.header+"</div>"; 
            headhtml+="<div id='act-div-right' class='act-retract-right'   style='width:15;'></div>";        
            this.tmpFlag4Act = true;
            newHeader = headhtml;
        }
        
        return newHeader;
    },
    getHeaderWidth : function(lClass,rClass){
        var width = 430;
        if(lClass.indexOf('collapse')!=-1) width-=123;
        if(rClass.indexOf('collapse')!=-1) width-=250;
        
        return (width<100)?100:width;
    },
    dealWithRetractHeader : function(infos){
        
        if(this.el.store.getCount()<=0) return;
        
        var _actCol = 2;
        
        if(infos.clicked!='center'){
            var actDiv   = (infos.clicked=='left')?this.retractL:((infos.clicked=='right')?this.retractR:this.retractC); 
            var oldClass = actDiv.dom.className;
            var newClass = (oldClass.indexOf('collapse')==-1)?oldClass+'-collapse':oldClass.replace('-collapse','');
            actDiv.dom.className = newClass;
            
            var nowWidth = this.getHeaderWidth(this.retractL.dom.className,this.retractR.dom.className);
            this.retractC.setWidth(nowWidth-40);
            this.el.getColumnModel().setColumnWidth(_actCol,nowWidth);
            
            for(var i=0;i<this.el.store.getCount();i++){
                var w = this.getAt(i,_actCol);
                if(infos.clicked=='left'){
                    if(newClass.indexOf('collapse')==-1){
                        w.showCode();
                    }else{
                        w.hideCode();
                    }
                }else{
                    if(newClass.indexOf('collapse')==-1){
                        w.showName();
                    }else{
                        w.hideName();
                    }
                }
            }
        }else{
            var cm    = this.el.getColumnModel();
            var width = cm.getColumnWidth(_actCol);
            var lDiv  = this.retractL.dom;
            var rDiv  = this.retractR.dom;

            if(width==430){
                lDiv.className = 'act-retract-left-collapse';
                rDiv.className = 'act-retract-right-collapse';
                
                this.retractC.setWidth(60);
                cm.setColumnWidth(_actCol,100);
                
                for(var i=0;i<this.el.store.getCount();i++){
                    var w = this.getAt(i,_actCol);
                    w.hideAll();
                }
            }else{
                lDiv.className = 'act-retract-left';
                rDiv.className = 'act-retract-right';
                this.retractC.setWidth(390);
                cm.setColumnWidth(_actCol,430);
                for(var i=0;i<this.el.store.getCount();i++){
                    var w = this.getAt(i,_actCol);
                    w.showAll();
                }
            }
        }
    },
    
    //=============================================================================================
    //=============================================================================================
    createWidgetElement:function(){
        //debugger;
        var r = this.bindRelation;
        if(r && r.col){
            this.itemsIndex = 0;
            var theObj = this;
            var fields=[],addFields= (r.field)?r.field:[]; 
            var _root= r.root, _id=(r.id)?r.id:"id",_sysflag = (r.sysflag)?r.sysflag:"sysFlag";

            this.smRowspan  = r.smRowspan;
            this.usePlugins = r.usePlugins;
            this.headers    = r.headers;
            this.recordDefine = [];
            
            //-----------------------------------------------------------------------------------------
            //构造field，构造store
            //-----------------------------------------------------------------------------------------
            fields = this.getFieldsFromCol(r.col); 
            if(!this.checkHave(_id,fields))          fields.push(_id);
            if(!this.checkHave(_sysflag,fields))     fields.push(_sysflag);
            
            for(var i=0,len=addFields.length;i<len;i++){
                if((typeof addFields[i]) =="object") this.recordDefine.push(addFields[i]);
                else this.recordDefine.push({name:addFields[i]});
            }
            for(var i=0,len=fields.length;i<len;i++){
                if(this.isAddField(fields[i],addFields)){continue;}
                this.recordDefine.push({name:fields[i]});
            }

            var _record = Ext.data.Record.create(this.recordDefine);
            var _reader = new Ext.data.JsonReader({
                    root: _root,
                    id:_id,
                    totalProperty: "dataset.totalRecords",
                    successProperty:"response"
                }, _record
            );
            
            var dataStore = new Ext.data.Store({url: theObj.url,reader: _reader});
            
            //-----------------------------------------------------------------------------------------
            //构造列模型
            //-----------------------------------------------------------------------------------------
            var newCMDefine = [];
            if(this.colNumber) {
                newCMDefine.push(new Ext.grid.RowNumberer());
            }
            if(this.colCheckbox) {
                var sm = new Ext.grid.CheckboxSelectionModel();
                if(this.smRowspan) sm.rowspan = this.smRowspan;
                newCMDefine.push(sm);
            }
            for(var i=0;i<r.col.length;i++){
                //r.col[i]["sortable"] = (r.col[i]["sortable"]!=undefined)?r.col[i]["sortable"]:true;
                r.col[i]["locked"] = false;
                r.col[i]["id"] = "col_"+i;
                r.col[i]["align"] = "center";
                r.col[i]["sortable"] = false;
                r.col[i]["resizable"] = false;
                r.col[i]["fixed"] = true;
                r.col[i]["css"] = "border-right:1px #EDEDED solid;align:left;";
                if(r.col[i].plugins!=undefined){        //处理列头扩展
                    if(r.col[i].plugins.act){
                        var newHeader = this.createHeaderByPlugins(r.col[i])
                        r.col[i].header = (newHeader=="")?r.col[i].header:newHeader;
                    }
                }

                newCMDefine.push(r.col[i]);
            }
            var newCM = new Ext.grid.ColumnModel(newCMDefine);
            
            //-----------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------
            var sm = null;
            if(this.singleSelect) sm = new Ext.grid.RadioSelectionModel({singleSelect:true});
            else sm = new Ext.grid.CheckboxSelectionModel();
            if(this.smRowspan) sm.rowspan = this.smRowspan;
            
            var gConfig = {
                stripeRows:true,//viewConfig: {autoFill:true},
                loadMask: true,store:dataStore,cm:newCM,sm:sm,
                enableDragDrop:false,
                enableColumnMove:false,
                width : this.width,
                height : this.height,
                renderTo : this.getOCD(),
                animCollapse:false
            };
            
            if(this.showTitle){
                gConfig.title = this.title;gConfig.iconCls = "icon-grid";
            }
            if(this.tbar){
                var index=0;
                if(this.tbar instanceof Array)
                    this.tbar.push({text: '　'});
                
                for(var i=0;i<this.tbar.length;i++){
                    if(this.tbar[i]=="-") continue;
                    this.tbar[i].id=this.btIDPrefix+index;
                    index++;
                    if(this.tbar[i].text=="新增") this.tbar[i].iconCls="grid_add";
                    else if(this.tbar[i].text=="删除") this.tbar[i].iconCls="grid_del";
                    else if(this.tbar[i].text=="　") this.tbar[i].iconCls="grid_null";
                    else this.tbar[i].iconCls="grid_bt";
                        
                    this.tbarButtons.push({text:this.tbar[i].text});
                }
                gConfig.tbar = this.tbar;
            }
            if(this.collapsible){
                gConfig.collapsible = this.collapsible;
            }
            
            var grid = new Ext.grid.GridPanel(gConfig);
            this.el  = grid;
            this.el.setWidth(this.OCD.offsetWidth);
            
            //-----------------------------------------------------------------------------------------
            //-----------------------------------------------------------------------------------------
            if(sc.isView()){
                for(var i=0,len=this.tbarButtons.length;i<len;i++){
                    var bt = this.getButton(this.tbarButtons[i]["text"]);
                    if(this.tbarButtons[i]["text"]!="　")
                        bt.hide();
                }
            }else{
                var bt = this.getButton("　");
                if(bt) bt.hide();
            }

            if(this.tmpFlag4Act){
                this.retractL = Ext.get('act-div-left');
                this.retractR = Ext.get('act-div-right');
                this.retractC = Ext.get('act-div-center');

                Ext.get('act-div-left').on('click',function(e,w){
                    theObj.dealWithRetractHeader({clicked:'left'});
                });
                
                Ext.get('act-div-right').on('click',function(e,w){
                    theObj.dealWithRetractHeader({clicked:'right'});
                });
                
                Ext.get('act-div-center').on('click',function(e,w){
                    theObj.dealWithRetractHeader({clicked:'center'});
                });
            }
            
            //-----------------------------------------------------------------------------------------
            //事件的变更
            //-----------------------------------------------------------------------------------------
            grid.getView().on('rowsinserted',this.afterRowInsert,this);
        }
    },
    
    //=============================================================================================
    //XGrid 处理方法
    //=============================================================================================
    haveEditor : function(row,col){
        return (this.items[row]!=undefined)?((this.items[row][col-this.bc]!=undefined)?true:false):false;
    },
    getEditor : function(row,col){
        return (this.haveEditor(row,col))?this.items[row][col-this.bc]:null;
    },
    getEditorType : function(row,col){
        if(this.bindRelation){
            return this.bindRelation.editor[col-this.bc].type;
        }
        return "";
    },
    getEditorConfig : function(row,col){
        if(this.bindRelation){
            return this.bindRelation.editor[col-this.bc].config;
        }
        return {};
    },
    
    clearCombox:function(column,row){
        var rlen = this.el.store.getCount();
        var begin = 0,end=rlen;
        if(row!=undefined){
            begin = row;
            end = row+1;
        }
        for(var i=begin;i<end;i++){
            var c = this.getEditor(i,column);
            //c.clearValue();                           //清显示值
            c.setValue('');
            this.setFieldValueByColumn(column,i,"");  //清数据集值（连带清数据结构）
        }
    },
    changeCombox: function(column,config,row){
        if(sc.isView()) return;
        var rlen = this.el.store.getCount();
        
        var begin = 0,end=rlen;
        if(row!=undefined){
            begin = row;
            end = row+1;
        }
        for(var i=begin;i<end;i++){
            var c = this.getEditor(i,column),_fields = [];
            
            if(c.store){
                if(c.store.proxy){
                    if(c.store.proxy.conn.url==config.url)  continue;   //URL相同，跳出
                }
            }
            
            if(config.clearValue!=undefined && config.clearValue){
                c.clearValue();                           //清显示值
                this.setFieldValueByColumn(column,i,"");  //清数据集值（连带清数据结构）
            }

            //----------------------------------------------------------------
            //----------------------------------------------------------------
            var _url = config.url;
            var _root       = (config.root)?config.root:"dataset.simplecombobox";
            var _textField  = (config.fieldText)?config.fieldText:"text";
            var _valueField = (config.fieldValue)?config.fieldValue:"code";
            
            _fields.push(_textField);
            _fields.push(_valueField);
            
            //20080817170900 于俊杰add
            //原因：由一个有数据集的combox变换为一个无数据集的combox时，
            //      如果不清除原有的store，默认的select方法出错
            c.store.removeAll();        
                            
            c.store.proxy= new Ext.data.HttpProxy({url: _url, method: 'POST'});
    	    c.store.reader= new Ext.data.JsonReader({root: _root}, _fields);
    
            c.valueField   = _valueField;        
            c.displayField = _textField;      
            c.store.load();
        }
    },

    createComboxStore : function(config){
        var store = null;
        var tf    = (config.fieldText)?config.fieldText:"text";
        var vf    = (config.fieldValue)?config.fieldValue:"code";
        var root  = (config.root)?config.root:"dataset.simplecombobox";
        
        if(config.url && config.url!=""){
            store = new Ext.data.Store({
    	        proxy: new Ext.data.HttpProxy({url: config.url}),
    	        reader: new Ext.data.JsonReader({root: root}, [tf,vf])
            });
            var _mode = (config.mode)?config.mode:"local";
            if(_mode!='remote') store.load();
        }
        else
            store = new Ext.data.SimpleStore({fields:[tf,vf],data : []});
            
        try{
            return store;
        }finally{
            store = null;
        }
    },
    
    createColEditor : function(view,row,col,wtype){     //创建TD编辑器
        if(this.haveEditor(row,col))    
            return this.getEditor(row,col);
        var theObj = this;
        
        var record = this.el.store.getAt(row);
        var _value = record.get(this.el.getColumnModel().config[col].dataIndex);
        
        var _name='';
        if(this.el.getColumnModel().config[col].nameIndex)
          _name  = record.get(this.el.getColumnModel().config[col].nameIndex);
        
        _name=(_name==undefined)?"":_name;  
        //debugger;
        //--------------------------------------------------------------------------------
        var editor  = null;
        var cell    = view.getCell(row,col);

        var config      = this.getEditorConfig(row,col);
        config.width    = cell.offsetWidth-3;
        config.height   = 20;
        config.renderTo = cell;
        config.focusClass = 'x-form-focus2';
        config.tabIndex = sc.tabindex;
        config.value    = (_value==undefined)?"":_value;

        //200808040752 修改全局对象保存为数组保存，故不需要ID
        //config.id     = 'r_'+row+'_c_'+col;
        config.id       = 'subwidget_'+this.itemsIndex;
        
        this.itemsIndex++;
        sc.tabindex++;
        if(wtype==undefined)    
            wtype = this.getEditorType(row,col);
        
        switch (wtype){
            //----------------------------------------------------------------------------
            case "textField":
                config.selectOnFocus = true;
                editor = new Ext.form.TextField(config);
                break;

            case "numberField":
                config.selectOnFocus = true;
                editor = new Ext.form.NumberField(config);
                break;

            //----------------------------------------------------------------------------
            case "comboBox":
                var createConfig = {                //构造默认的config定义
                    store         : this.createComboxStore(config),
                    name          : (config.fieldText)?config.fieldText:"text",
                    displayField  : (config.fieldText)?config.fieldText:"text",
                    valueField    : (config.fieldValue)?config.fieldValue:"code",
                    autoShow      : false,
                    readOnly      : false,
                    forceSelection: true,
                    typeAhead     : true,
                    triggerAction : 'all',
                    loadingText   : "读取...",
                    emptyText     : '未选择...',
                    selectOnFocus : true,
                    //editable      : (config.editable)?config.editable:true,
                    listWidth     : (config.listWidth)?config.listWidth:200,
                    maxHeight     : (config.maxHeight)?config.maxHeight:200,
                    mode          : (config.mode)?config.mode:'local'
                };
                Ext.apply(createConfig,config);     //从用户定义复制配置信息
                editor = new Ext.form.ComboBox(createConfig);
                
                editor.setValue(_value);
                editor.el.dom.value=_name;
    	          editor.lastSelectionText = _name;
                editor.el.removeClass("x-form-empty-field");    	

                break;

            //----------------------------------------------------------------------------
            case "dateField":
                var createConfig = {                //构造默认的config定义
                    format:"Y-m-d",
                    readOnly:true,
                    forceSelection: true,
                    emptyText:"选择日期"
                };
                Ext.apply(createConfig,config);     //从用户定义复制配置信息
                editor = new Ext.form.DateField(createConfig);;
                break;

            //----------------------------------------------------------------------------
            case "selectfield":
                var createConfig = {                //构造默认的config定义
                    blankText  : "未选择...",
                    showValue  : (config.text)?config.text:"text",
                    dataValue  : (config.value)?config.value:"id"
                };
                Ext.apply(createConfig,config);     //从用户定义复制配置信息
                editor = new Ext.form.SelectField(createConfig);;
                break;
            
            case "selectfieldadvanced":
                var createConfig = {                //构造默认的config定义
                    blankText  : "未选择...",
                    showValue  : (config.text)?config.text:"text",
                    dataValue  : (config.value)?config.value:"id"
                };
                Ext.apply(createConfig,config);     //从用户定义复制配置信息
                editor = new Ext.form.SelectFieldAdvanced(createConfig);;
                editor.setAdvanced(_name);
                break;

        }
        
        //200808040752 修改全局对象保存为数组保存，故修改保存方式
        //this.items[config.id] = editor;
        if(this.items[row]==undefined) this.items[row] = [];
        this.items[row][col-this.bc] = editor;
        
        editor.el.on("keyup", this.onKeyUp, this);
        editor.on('blur',this.onBlur,this);

        //----------------------------------------------------------------------------
        //组建创建后，根据eventManager为之追加事件
        //----------------------------------------------------------------------------
        //debugger;
        
        var ems = this.getEvent(col);
        
        for(var i=0;i<ems.length;i++){
            var em = this.eventManager[ems[i]];
            if(em!=null){
                switch (wtype){
                    case "selectfieldadvanced":
                        if(em.ename=='beforeclick'){
                            editor.addListener(em.ename,function(sf){
                                var _data  =sf.getDataObj();
                                return em.fn.call("",_data,row,editor);
                            });
                        }
                        break;
                    case "comboBox":
                        if(em.ename=='beforeclick'){
                            eval("var tf = function(o){ \n"
                                +"  return theObj.eventManager["+ems[i]+"].fn.call('',row,editor);;\n"
                                +"}\n");
                            editor.addListener('beforeclick',tf);
                        }else if(em.ename=='select'){
                            editor.addListener('select',function(cb,r,i){
                                //debugger;
                                var t = r.get(editor.displayField);
                                var v = r.get(editor.valueField);
                                em.fn.call('',t,v,row,cb);
                            });
                        }
                        break;
                }
            }
        }
        /*        
        for(var i=0;i<this.eventManager.length;i++){
            var em = this.eventManager[i];
            if(em.column==col){
                switch (wtype){
                    case "selectfieldadvanced":
                        editor.addListener(em.ename,function(sf){
                            var _data  =sf.getDataObj();
                            em.fn.call("",_data,row,editor);
                        });
                        break;
                    case "comboBox":
                        if(em.ename=='beforeclick'){
                            editor.addListener(em.ename,function(o){
                                em.fn.call("",row,editor);
                            });
                        }
                        break;
                }
            }
        }
        */
        return editor;        
    },
    getEvent : function(col){
        var r = [];
        for(var i=0;i<this.eventManager.length;i++){
            if(this.eventManager[i].column==col)
                r.push(i);
        }
        return r;
    },
    
    onBlur : function(field){
        var place = this.getRowColFromID(field.id);

        if(field.getXType()=="selectfieldadvanced"){
            var cm = this.el.getColumnModel();
            if(cm.config[place.col].nameIndex){
                this.setFieldValueByDataIndex(cm.config[place.col].nameIndex,place.row,field.getAdvanced());
            }
        }

        this.setFieldValueByColumn(place.col,place.row,field.getValue());
        this.afterOnBlur(place.row,place.col,field.startValue,field.getValue(),field);
    },
    afterOnBlur : function(row,col,oldValue,newValue,field){
        //alert();
    },
    
    onKeyUp : function(e){
        if(e.getKey()==13){
            var place    = this.getPlace(e.getTarget().id);
            var nowItem  = this.getAt(place.row,place.col);
            var nextItem = this.getNext(place.row,place.col);
            
            if(nowItem.triggerBlur)
                nowItem.triggerBlur();
            else
                nowItem.blur();
                
            nextItem.focus();
        }
    },

    //=============================================================================================
    //事件添加删除
    //=============================================================================================
    addListener2Editor : function(_col,_ename,_fn){
        this.eventManager.push({
            column:_col,
            ename:_ename,
            fn : _fn
        });
    },
    
    //=============================================================================================
    //数据编辑
    //=============================================================================================
    getNowEditInfo : function(){
        //return this.nowEditInfo;
    },
    
    getFieldValueByColumn : function(column,row){
        var cm = this.el.getColumnModel();
        var dataIndex = cm.config[column].dataIndex;
        return this.getFieldValueByDataIndex(dataIndex,row);
    },
    getFieldValueByDataIndex : function(dataIndex,row){
        return this.el.store.getAt(row).get(dataIndex);
    },
    getStore : function(){
        return this.el.store;
    },
    
    setFieldValueByColumn : function(column,row,newValue){
        var cm = this.el.getColumnModel();
        if(cm.config[column].dataIndex){
            this.setFieldValueByDataIndex(cm.config[column].dataIndex,row,newValue);
        }
        /*
        if(cm.config[column].nameIndex){
            this.setFieldValueByDataIndex(cm.config[column].nameIndex,row,newValue);
        }*/
    },
    
    setFieldValueByDataIndex:function(dataIndex,row,newValue){
        var record = this.el.getStore().getAt(row);
        if(record){
            record.editing = true;
            record.set(dataIndex,newValue);
            var theObj = this;        
            var dataObj = sc.getObjFromBusiness(theObj.bindRelation["data"]+"."+theObj.bindRelation["result"]);   //取子对象
            sc.setBusinessData(dataObj,row,dataIndex,newValue);    //保存到数据结构
        }
    },
    
    //=============================================================================================
    //XGrid 处理方法
    //=============================================================================================
    getFactualRow : function(index,colCount){
        var row = parseInt(index/colCount,10);
        for(var i=0;i<this.delIndex.length;i++){
            if(this.delIndex[i][1]< index)
                row--;
        }
        return row;
    },
    
    getRowColFromID : function(id){
        //delIndex
        var count = this.el.colModel.getColumnCount()-this.bc;
        var index = parseInt(id.split('_')[1],10);
        var _row  = this.getFactualRow(index,count);
        var robj  = {row:_row,col:index%count+2};
        return robj;
    },
    getPlace : function(wid){
        return this.getRowColFromID(wid);
    },
    getAt : function(row,col){
        return this.getEditor(row,col);
    },
    
    getNext : function(row,col){
        var cm = this.el.colModel, clen = cm.getColumnCount();
        var ds = this.el.store, rlen = ds.getCount();
        col++;
        if(col >= clen){
            row++;
            col=this.bc;
            row = (row>=rlen)?0:row;
        }
        return this.getAt(row,col);
    },

    getSelectedIndexs : function(){
        //debugger;
        var sm = this.el.selModel;
        var theObj = this;
        if(arguments.length==0){
            return [].concat((sm.selectedIndexs)?sm.selectedIndexs:[]);
        }else{
            var rArray = [].concat((sm.selectedIndexs)?sm.selectedIndexs:[]);
            rArray = rArray.sort(theObj.mysort);
            return rArray;
        }
    },
    clearSelectedIndexs : function(){
        var sm = this.el.selModel;
        sm.selectedIndexs = [];
    },
    mysort:function(a,b){
        return (a>b)?-1:1;
    },
    
    //=============================================================================================
    //XGrid 处理方法
    //=============================================================================================
    getRecord : function(row){
        return this.el.store.getAt(row);
    },
    addRecords : function(recordArray){
        if(recordArray instanceof Array)
            for(var i=0;i<recordArray.length;i++)
                this.addnewRecord2Grid(recordArray[i]);
        else
            this.addnewRecord2Grid(recordArray);
        return;
    },
    addRecordByButton : function(){
        var dsDefine= this.recordDefine;
        var colInfo = Ext.data.Record.create(dsDefine);
        var cd = {};
        for(var i=0;i<dsDefine.length;i++){
            if(dsDefine[i].type=="date"){
                cd[dsDefine[i].name] = new Date();
            }else{
                cd[dsDefine[i].name] = (dsDefine[i].defaultValue)?dsDefine[i].defaultValue:"";
            }
        }
        var p = new colInfo(cd);
        this.addnewRecord2Grid(p);
    },
    addnewRecord2Grid : function(p){
        var _index = this.el.store.getCount();

        if(arguments.length==2){
          this.el.store.insert(_index, p);
          return ;
        }
        
        var results = sc.getObjFromBusiness(this.bindRelation["data"]+"."+this.bindRelation["result"]);
        //-----------------------------------------------------------------------------
        //传值传引用啊...
        //-----------------------------------------------------------------------------
        var o2business = {};
        Ext.apply(o2business,p.data);
        for(var pr in o2business){
            if(typeof o2business[pr] =='object' && pr!='toJSONString'){
                if(o2business[pr] instanceof Date){
    	            var copyDate = o2business[pr].clone();
  	                var strDate = copyDate.format('Ymd');
	                o2business[pr] = strDate;
              	}
            }
        }
        
        if(results instanceof Array){
            results.push(o2business);
        }else{
            if(sc.isAdd()){
                var dataroot = sc.getObjFromBusiness(this.bindRelation["data"]);
                dataroot[this.bindRelation["result"]]= new Array();  
                dataroot[this.bindRelation["result"]].push(o2business);
            }else{
                var tmpobj = {};
                Ext.apply(tmpobj,results);
                var dataroot = sc.getObjFromBusiness(this.bindRelation["data"]);

                dataroot[this.bindRelation["result"]]= new Array();                
                dataroot[this.bindRelation["result"]].push(tmpobj);
                dataroot[this.bindRelation["result"]].push(o2business);
            }
        }        
        
        this.el.store.insert(_index, p);
    },
    removeRecord : function(){
        if(!(arguments.length==1 && arguments[0]==false)){
            //if(this.el.getSelections()) 
            
            var dels = this.el.getSelections();
            if(dels.length>0)
            {
                if(!confirm('真的要删除所选择的数据吗？')){
                    return;
                }
            }else{
                Ext.Msg.alert("提示：","请先选择记录，再进行删除操作！");
                return;
            }
        }
        //-----------------------------------------------------------------------
        //-----------------------------------------------------------------------
        this.fieldID    = (this.bindRelation.id)?this.bindRelation.id:"id";
        this.fieldFlag  = (this.bindRelation.sysflag)?this.bindRelation.sysflag:"sysFlag";
        
        eval("var dataObj = Sail.data.business."+this.bindRelation["data"]);
        var sdata = this.el.getSelections();
        var idata = this.getSelectedIndexs('sort');
        for(var i=0;i<idata.length;i++){
            this.deleteWidgetFromRow(idata[i]);
        }
        this.clearSelectedIndexs();
        
        for(var i=0;i<sdata.length;i++){
            var index = this.el.store.data.indexOf(sdata[i]);
            
            var results = dataObj[this.bindRelation["result"]];
            index = sc.getActualRow(results,index);
            try{
                if(sdata[i].get(this.fieldID)==""){
                    if(results instanceof Array)
                        dataObj[this.bindRelation["result"]].splice(index,1);
                    else
                        dataObj[this.bindRelation["result"]]=[];
                }else{
                    if(results instanceof Array)
                        dataObj[this.bindRelation["result"]][index][this.fieldFlag]="0";
                    else
                        dataObj[this.bindRelation["result"]][this.fieldFlag]="0";;
                }
            }catch(e){
                alert("删除记录时发生异常！");
            }

            this.el.store.remove(sdata[i]);
        }
        this.refreshNumber();
    },
    removeAll : function(){
        var sm = this.el.getSelectionModel();
        sm.selectAll();
        this.removeRecord();
    },
    deleteWidgetFromRow : function(row){
        try{
            var bIndex,eIndex;
            for(var i=0;i<this.items[row].length;i++){
                var w = this.items[row][i];
                if(w.destroy!=undefined){
                    w.destroy();
                }
                if(i==0) bIndex = parseInt(w.id.split("_")[1],10);
                if(i==this.items[row].length-1) eIndex = parseInt(w.id.split("_")[1],10);
    
            }
            this.items.splice(row,1);
            var delInfo = [bIndex,eIndex];
            this.delIndex.push(delInfo);
        }catch(e){
        }   
    },
    refreshNumber : function(){
        var count = this.el.store.getCount();
        for(var i=0;i<count;i++){
            var cell = this.el.getView().getCell(i,0);
            cell.children[0].innerText = ""+(i+1);
        }
    },
                
    afterRowInsert : function(view,first,last){

          var cm    = this.el.getColumnModel();
          var width = cm.getColumnWidth(2);
          var lDiv  = this.retractL.dom;
          var rDiv  = this.retractR.dom;

          if(width!=430){
              lDiv.className = 'act-retract-left';
              rDiv.className = 'act-retract-right';
              this.retractC.setWidth(390);
              cm.setColumnWidth(2,430);
          }
        

        var len = this.el.colModel.getColumnCount()
        for(var i=2;i<len;i++){
            var cell = view.getCell(first,i);
            this.createColEditor(view,first,i);
        }
    }

});












//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
Ext.override(Ext.grid.GridView,{
    initTemplates : function(){
        var ts = this.templates || {};
        if(!ts.master){
            ts.master = new Ext.Template(
                    '<div class="x-grid3" hidefocus="true">',
                        '<div class="x-grid3-viewport">',
                            '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset">{header}</div></div><div class="x-clear"></div></div>',
                            '<div class="x-grid3-scroller"><div class="x-grid3-body">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
                        "</div>",
                        '<div class="x-grid3-resize-marker">&#160;</div>',
                        '<div class="x-grid3-resize-proxy">&#160;</div>',
                    "</div>"
                    );
        }

        if(!ts.header){
            ts.header = new Ext.Template(
                    '<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
                    '<thead><tr class="x-grid3-hd-row">{cells}</tr></thead>',
                    "</table>"
                    );
        }

        if(!ts.hcell){
            ts.hcell = new Ext.Template(
                    '<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id}" style="{style}"><div {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '',
                    '{value}',
                    "</div></td>"
                    );
        }

        if(!ts.body){
            ts.body = new Ext.Template('{rows}');
        }

        if(!ts.row){
            ts.row = new Ext.Template(
                    '<div class="x-grid3-row {alt}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
                    '<tbody><tr>{cells}</tr>',
                    (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="-1" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''),
                    '</tbody></table></div>'
                    );
        }

        if(!ts.cell){
            ts.cell = new Ext.Template(
                    '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="-1" {cellAttr}>',
                    '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>',
                    "</td>"
                    );
        }

        for(var k in ts){
            var t = ts[k];
            if(t && typeof t.compile == 'function' && !t.compiled){
                t.disableFormats = true;
                t.compile();
            }
        }

        this.templates = ts;

        this.tdClass = 'x-grid3-cell';
        this.cellSelector = 'td.x-grid3-cell';
        this.hdCls = 'x-grid3-hd';
        this.rowSelector = 'div.x-grid3-row';
        this.colRe = new RegExp("x-grid3-td-([^\\s]+)", "");
    },
    
    refresh : function(headersToo){
        this.fireEvent("beforerefresh", this);
        this.grid.stopEditing();

        var result = this.renderBody();
        this.mainBody.update(result);

        if(headersToo === true){
            this.updateHeaders();
            this.updateHeaderSortState();
        }
        this.processRows(0, true);
        this.layout();
        this.applyEmptyText();
        this.fireEvent("refresh", this);
    },
    renderRows : function(startRow, endRow){
        // pull in all the crap needed to render rows
        var g = this.grid, cm = g.colModel, ds = g.store, stripe = g.stripeRows;
        var colCount = cm.getColumnCount();

        if(ds.getCount() < 1){
            return "";
        }

        var cs = this.getColumnData();

        startRow = startRow || 0;
        endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;

        // records to render
        var rs = ds.getRange(startRow, endRow);
        return this.doRender(cs, rs, ds, startRow, colCount, stripe);
    },
    doRender : function(cs, rs, ds, startRow, colCount, stripe){
        var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1;
        var tstyle = 'width:'+this.getTotalWidth()+';';
        // buffers
        var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r;
        for(var j = 0, len = rs.length; j < len; j++){
            r = rs[j]; cb = [];
            var rowIndex = (j+startRow);
            //debugger;
            for(var i = 0; i < colCount; i++){
                if(i>=2){
                    ct = new Ext.Template(
                    '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="-1" {cellAttr}>',
                    "</td>"
                    );                
                }
                c = cs[i];
                p.id = c.id;
                p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');
                p.attr = p.cellAttr = "";
                p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
                p.style = c.style;
                if(p.value == undefined || p.value === "") p.value = "&#160;";
                if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
                    p.css += ' x-grid3-dirty-cell';
                }
                cb[cb.length] = ct.apply(p);
            }
            var alt = [];
            if(stripe && ((rowIndex+1) % 2 == 0)){
                alt[0] = "x-grid3-row-alt";
            }
            if(r.dirty){
                alt[1] = " x-grid3-dirty-row";
            }
            rp.cols = colCount;
            if(this.getRowClass){
                alt[2] = this.getRowClass(r, rowIndex, rp, ds);
            }
            rp.alt = alt.join(" ");
            rp.cells = cb.join("");
            buf[buf.length] =  rt.apply(rp);
        }
        return buf.join("");
    },
    
    getColumnStyle : function(col, isHeader){
        //debugger;
        var style = !isHeader ? (this.cm.config[col].css || '') : '';
        style += 'width:'+this.getColumnWidth(col)+';';
        if(this.cm.isHidden(col)){
            style += 'display:none;';
        }
        var align = this.cm.config[col].align;
        if(align){
            if(isHeader)
                style += 'text-align:'+align+';';
            else
                style += 'text-align:left;padding-left:2px';
        }
        return style;
    },
    
    insertRows : function(dm, firstRow, lastRow, isUpdate){
        if(firstRow === 0 && lastRow == dm.getCount()-1){
            this.refresh();
            this.fireEvent("rowsinserted", this, firstRow, lastRow);
            this.processRows(firstRow);
        }else{
            if(!isUpdate){
                this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
            }
            var html = this.renderRows(firstRow, lastRow);
            var before = this.getRow(firstRow);
            if(before){
                Ext.DomHelper.insertHtml('beforeBegin', before, html);
            }else{
                Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html);
            }
            
            if(!isUpdate){
                this.fireEvent("rowsinserted", this, firstRow, lastRow);
                this.processRows(firstRow);
            }
        }
    },    
    onCellSelect : function(row, col){
        var cell = this.getCell(row, col);
        if(cell){
            this.fly(cell).addClass("x-grid3-cell-selected");
        }
    },
    focusRow : function(row){
        return;
        //debugger;
        this.focusCell(row, 0, false);
    },
    renderHeaders : function(){
	    var cm = this.cm, ts = this.templates;
        var ct = ts.hcell;

        var cb = [], sb = [], p = {};

        for(var i = 0, len = cm.getColumnCount(); i < len; i++){
            p.id = cm.getColumnId(i);
            p.value = cm.getColumnHeader(i) || "";
            p.style = this.getColumnStyle(i, true);
            if(cm.config[i].align == 'right'){
                p.istyle = 'padding-right:16px';
            }
            p.istyle = cm.config[i].istyle;
            cb[cb.length] = ct.apply(p);
        }
        return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'});
	}

});


Ext.override(Ext.grid.CellSelectionModel,{
    handleMouseDown : function(g, row, cell, e){
        if(e.button !== 0 || this.isLocked()){
            return;
        };
        this.select(row, cell,true);
    },
    select : function(rowIndex, colIndex, preventViewNotify, preventFocus, /*internal*/ r){
        if(this.fireEvent("beforecellselect", this, rowIndex, colIndex) !== false){
            this.clearSelections();
            r = r || this.grid.store.getAt(rowIndex);
            this.selection = {
                record : r,
                cell : [rowIndex, colIndex]
            };
            if(!preventViewNotify){
                var v = this.grid.getView();
                v.onCellSelect(rowIndex, colIndex);
                if(preventFocus !== true){
                    v.focusCell(rowIndex, colIndex);
                }
            }
            this.fireEvent("cellselect", this, rowIndex, colIndex);
            this.fireEvent("selectionchange", this, this.selection);
        }
    }
});


Ext.override(Ext.grid.RowSelectionModel,{

    initEvents : function(){
        if(!this.grid.enableDragDrop && !this.grid.enableDrag){
            this.grid.on("rowmousedown", this.handleMouseDown, this);
        }else{ // allow click to work like normal
            this.grid.on("rowclick", function(grid, rowIndex, e) {
                if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
                    this.selectRow(rowIndex, false);
                    grid.view.focusRow(rowIndex);
                }
            }, this);
        }
        
        this.grid.getGridEl().on(Ext.isIE ? "keydown" : "keypress", this.handleKeyDown, this);

        /*
        this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), {
            "up" : function(e){
                //debugger;
                window.event.keyCode=9;
                //e.keyCode = 9;
                return;
                if(!e.shiftKey){
                    this.selectPrevious(e.shiftKey);
                }else if(this.last !== false && this.lastActive !== false){
                    var last = this.last;
                    this.selectRange(this.last,  this.lastActive-1);
                    this.grid.getView().focusRow(this.lastActive);
                    if(last !== false){
                        this.last = last;
                    }
                }else{
                    this.selectFirstRow();
                }
            },
            "down" : function(e){
                if(!e.shiftKey){
                    this.selectNext(e.shiftKey);
                }else if(this.last !== false && this.lastActive !== false){
                    var last = this.last;
                    this.selectRange(this.last,  this.lastActive+1);
                    this.grid.getView().focusRow(this.lastActive);
                    if(last !== false){
                        this.last = last;
                    }
                }else{
                    this.selectFirstRow();
                }
            },
            scope: this
        });
        */
        
        var view = this.grid.view;
        view.on("refresh", this.onRefresh, this);
        view.on("rowupdated", this.onRowUpdated, this);
        view.on("rowremoved", this.onRemove, this);
    },
    handleKeyDown : function(e){
        
        //debugger;
        //var k = e.getKey()
        //this.browserEvent;
        //debugger;
        
        return;             //20080814203200 于俊杰处理，保证回车跳转
        e.keyCode = 9;
        
        if(!e.isNavKeyPress()){
            return;
        }
        var g = this.grid, s = this.selection;
        if(!s){
            e.stopEvent();
            var cell = g.walkCells(0, 0, 1, this.isSelectable,  this);
            if(cell){
                this.select(cell[0], cell[1]);
            }
            return;
        }
        var sm = this;
        var walk = function(row, col, step){
            return g.walkCells(row, col, step, sm.isSelectable,  sm);
        };
        var k = e.getKey(), r = s.cell[0], c = s.cell[1];
        var newCell;

        switch(k){
             case e.TAB:
                 if(e.shiftKey){
                     newCell = walk(r, c-1, -1);
                 }else{
                     newCell = walk(r, c+1, 1);
                 }
             break;
             case e.DOWN:
                 newCell = walk(r+1, c, 1);
             break;
             case e.UP:
                 newCell = walk(r-1, c, -1);
             break;
             case e.RIGHT:
                 newCell = walk(r, c+1, 1);
             break;
             case e.LEFT:
                 newCell = walk(r, c-1, -1);
             break;
             case e.ENTER:
                 if(g.isEditor && !g.editing){
                    g.startEditing(r, c);
                    e.stopEvent();
                    return;
                }
             break;
        };
        if(newCell){
            this.select(newCell[0], newCell[1]);
            e.stopEvent();
        }
    },

    handleMouseDown : function(g, rowIndex, e){
        //debugger;
        if(e.button !== 0 || this.isLocked()){
            return;
        };
        var view = this.grid.getView();
        if(e.shiftKey && this.last !== false){
            var last = this.last;
            this.selectRange(last, rowIndex, e.ctrlKey);
            this.last = last; // reset the last
            view.focusRow(rowIndex);
        }else{
            var isSelected = this.isSelected(rowIndex);
            if(e.ctrlKey && isSelected){
                this.deselectRow(rowIndex);
            }else if(!isSelected || this.getCount() > 1){
                this.selectRow(rowIndex, e.ctrlKey || e.shiftKey);
                view.focusRow(rowIndex);
            }
        }
    },
    
    selectRow : function(index, keepExisting, preventViewNotify,stopEvent){
        //debugger;
        if(this.locked || (index < 0 || index >= this.grid.store.getCount())) return;
        var r = this.grid.store.getAt(index);
        if(r && this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false){
            if(!keepExisting || this.singleSelect){
                this.clearSelections();
            }
            //---------------------------------------------------------------
            //20080814163500 于俊杰扩展
            //处理：选择时，记录被点击记录索引
            //成因：连续增加空行并选择删除时 store.data.indexOf(r)索引相同
            //---------------------------------------------------------------
            if(this.selectedIndexs==undefined) this.selectedIndexs = [];
            this.selectedIndexs.push(index);
            //---------------------------------------------------------------
            //over
            //---------------------------------------------------------------
            
            this.selections.add(r);
            this.last = this.lastActive = index;
            //debugger;
            if(!preventViewNotify){
                this.grid.getView().onRowSelect(index);
            }
            if(!stopEvent){
                this.fireEvent("rowselect", this, index, r);
                this.fireEvent("selectionchange", this);
            }
        }
    },
    clearSelections : function(fast){
        if(this.locked) return;
        if(fast !== true){
            var ds = this.grid.store;
            var s = this.selections;
            s.each(function(r){
                this.deselectRow(ds.indexOfId(r.id));
            }, this);
            s.clear();
        }else{
            this.selections.clear();
        }
        //---------------------------------------------------------------
        //20080814163500 于俊杰扩展
        //处理：清空选择
        //成因：连续增加空行并选择删除时 store.data.indexOf(r)索引相同
        //---------------------------------------------------------------
        this.selectedIndexs=[];
        //---------------------------------------------------------------
        //over
        //---------------------------------------------------------------
        
        this.last = false;
    },
    
    deselectRow : function(index, preventViewNotify){
        if(this.locked) return;
        if(this.last == index){
            this.last = false;
        }
        if(this.lastActive == index){
            this.lastActive = false;
        }
        var r = this.grid.store.getAt(index);
        if(r){
            this.selections.remove(r);
            
            //---------------------------------------------------------------
            //20080814163500 于俊杰扩展
            //目的：处理store.data.indexOf(r) 返回相同索引的问题
            //成因：连续增加空行并选择删除时 store.data.indexOf(r)索引相同
            //---------------------------------------------------------------
            if(this.selectedIndexs==undefined) this.selectedIndexs = [];
            for(var i=0;i<this.selectedIndexs.length;i++){
                if(this.selectedIndexs[i]==index)
                    this.selectedIndexs.splice(i,1);
            }
            //---------------------------------------------------------------
            //over
            //---------------------------------------------------------------
            
            if(!preventViewNotify){
                this.grid.getView().onRowDeselect(index);
            }
            this.fireEvent("rowdeselect", this, index, r);
            this.fireEvent("selectionchange", this);
        }
    }
});




